<template>
  <div class="bigbox">
    <div class="leftbox">
      <div>
        <el-autocomplete
          class="inline-input"
          size="small"
          v-model="filterText"
          style="margin-bottom: 10px;width:100%"
          :fetch-suggestions="querySearch"
          placeholder="输入关键字进行过滤"
          :trigger-on-focus="true"
          value-key="name"
          :debounce='300'
          @select="handleSelect">
        </el-autocomplete>
      </div>
      <div class="treebox">
        <el-tree
          :props="props"
          :load="loadNode"
          :highlight-current="true"
          lazy
          node-key="id"
          :default-expanded-keys="array"
          @node-click="handleNodeClick"
          ref="tree">
          <template slot-scope="{ node, data }">
            <span>
             <img
              :src="'data:image/png;base64,' + data.iconBase64"
              style="
                width: 16px;
                height: 16px;
                margin-right: 5px;
                vertical-align: bottom;"/> {{ node.label }}</span>
          </template>
        </el-tree>
      </div>
    </div>
    <div class="bodybox">
      <div class="sousuo">
        <el-form ref="form" label-position="left" label-width="60px">
            <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="日期">
                    <el-date-picker
                      v-model="valueri"
                      size="small"
                      type="datetimerange"
                      range-separator=""
                      value-format="yyyy-MM-dd HH:mm:ss"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12" style="text-align: right;">
                  <el-form-item label="">
                    <el-button size="small" @click="chongzhi">重 置</el-button>
                    <el-button size="small" type="primary" @click="submit">查 询</el-button>
                  </el-form-item>
                </el-col>
            </el-row>
        </el-form>
      </div>
      <div class="xunhuan">
        <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
          <el-checkbox v-for="(item,index) in leilist" :label="item.value" :key="index">{{item.text}}</el-checkbox>
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
        </el-checkbox-group>
        
      </div>
      <div class="zhuti">
        <!-- 封装表头导出刷新等功能 -->
        <div class="toptitle">
          <div><span>{{ devicename }}</span></div>
          <div><TopTitle @command="command" @daochu="daochu" @shuaxin="shuaxin"></TopTitle></div>
        </div>
        <!-- 封装表格 -->
        <div class="table">
          <TableColumn :issize="iissize" :tableConfig="tableConfig"
           :tableData="tableData" ref="tablecolumn">
          </TableColumn>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { saveAs } from 'file-saver'
import { getgenjiedianapi, getzijidianapi } from '../../../api/monitor'
import {getzidianxialaapi} from '../../../api/guidelines'
import { getKeywordListApi } from '@/api/Ledger'
import {getduogecedianapi,exportdeviceapi} from '@/api/analysis'
import TopTitle from '@/components/TopTitle'
import TableColumn from '@/components/Table'
export default {
  name: 'CallPoliceIndex',
  components: {
    TopTitle,
    TableColumn
},
  data() {
    return {
      checkedCities:[],
      checkAll: false,
      isIndeterminate: true,
      devicename:'',
      iissize:'medium',
      props: {
        label: 'name',
        children: 'children',
        isLeaf: 'leaf'
      },
      array: [],
      valueri:'',
      filterText: '',
      tableData:[],
      tableConfig: [
        { label: '时间', prop: 'time',width: '150'  ,center:'center'},
        // { label: 'A项电流', prop: 'orgName'},
        // { label: 'B项电流', prop: 'businessTypeName'},
      ],
      leilist: [],
      deviceIds:''
    };
  },

  async mounted() {
    this.gettime()
    const res = await getzidianxialaapi({ dictType: 'PDYW_CDBS' })
    this.leilist = res.data.list
    this.checkedCities=this.leilist.map(ele=>ele.value)
  },

  methods: {
    // 获取表格数据
    async gettablelist(id) {
      this.$refs.tablecolumn.loadind=true
      const res = await getduogecedianapi({
        deviceIds: id,
        itemTags: this.checkedCities.join(','),
        startTime: this.valueri[0],
        endTime:this.valueri[1]
      })
      this.tableConfig=[{ label: '时间', prop: 'time',width: '150' ,center:'center' },]
      for (let i = 0; i < this.checkedCities.length; i++){
        this.tableConfig.push({label:res.data.list[i].itemTagName,prop:this.checkedCities[i],center:'right'})
      }
      // 获取timePoints的长度
      this.tableData=[]
      var timePointsLength = res.data.list[0].timePoints.length;

      // 遍历timePoints数组
      for (var i = 0; i < timePointsLength; i++) {
          var newObj = {
              time: res.data.list[0].timePoints[i]
          };
          // 遍历list中的每个对象
          res.data.list.forEach(function(item) {
              newObj[item.itemTag] = item.itemPoints[i];
          });
          // 输出新数组
          this.tableData.push(newObj);
      }
      this.$refs.tablecolumn.loadind=false
    },
    // 树节点搜索
     async querySearch (queryString, cb) {
      const res = await getKeywordListApi({ name: queryString })
      const restaurants = res.data.list
      cb(restaurants)
      // 调用 callback 返回建议列表的数据
    },
    // 点击input输入建议
    handleSelect(item) {
      const newarr=item.pathId.split(',')
      for (let i = 0;i<newarr.length;i++) {
        if (newarr[i]) {
          this.array.push(newarr[i])
        }
      }
      function getgaoliang(that) {
        let node = that.$refs.tree.getNode(item);
        if (node) {
          that.$refs.tree.setCurrentKey(item.id);
        } else {
          setTimeout(() => {
            getgaoliang(that)
          }, 500);
        }
        }
      getgaoliang(this)
      this.handleNodeClick(item)
    },
    // 树节点点击事件
    handleNodeClick(val) {
      this.gettablelist(val.id)
      this.deviceIds=val.id
      this.devicename=val.name.replace(/\[.*?\]|\(.*?\)/g, '');
    },
    // 设备树懒加载
    async loadNode (node, resolve) {
      const res = await getgenjiedianapi({ treeModel: 'DeviceManageTree' })
      // const res = await getzijidianapi()
      const ress = await getzijidianapi(res.data.list[0])
      if (node.level === 0) { // 初始的级数（最顶层）
        this.devicename = ress.data.list[0].name
        this.deviceIds=ress.data.list[0].id
        this.gettablelist(ress.data.list[0].id)
        resolve(ress.data.list) 
        
        return this.$refs.tree.setCurrentKey(ress.data.list[0].id);
        // 最顶层数据渲染为region
      }
      if (node.level === 1) {
        
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      } else if (node.level === 2) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      } else if (node.level === 3) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      } else if (node.level === 4) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      } else if (node.level === 5) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      } else if (node.level === 6) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      }
    },
    // 表格密度调节
    command(val) {
      if (val === '默认') {
        this.iissize = 'medium'
      } else if (val === '中等') {
        this.iissize = 'small'
      } else {
        this.iissize = 'mini'
      }
    },
    // 导出
    async daochu() {
      const res = await exportdeviceapi({
        deviceIds: this.deviceIds,
        itemTags: this.checkedCities.join(','),
        startTime: this.valueri[0],
        endTime: this.valueri[1],
        isParams: true
      })
      console.log(res);
      const blobContent = new Blob([res])
      let url = window.URL.createObjectURL(blobContent)
      saveAs(url, '历史数据查询.xls')
     },
    // 刷新
    shuaxin() {
      this.gettablelist(this.deviceIds)
      this.$message.success('列表刷新成功')
     },
    // 查询
    submit() {
      if(!this.checkedCities.length) return this.$message.warning('请先勾选测点')
      this.gettablelist(this.deviceIds)
    },
    // 重置
    chongzhi() {
      this.checkedCities=[]
      this.checkedCities.push(this.leilist[0].value)
      this.gettime()
      this.gettablelist(this.deviceIds)
    },
      // 获取当前时间戳
    gettime() {
      this.valueri=[]
      const date = new Date()
      const year = date.getFullYear() // 年
      const month = date.getMonth() + 1 // 月
      const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate() //日

      date.setDate(date.getDate() - 1); // 获取昨天的日期
      // 获取昨天的年月日
      var yesterdayYear = date.getFullYear();
      var yesterdayMonth = date.getMonth() + 1; // 月份是从0开始的，所以要加1
      var yesterdayDay = date.getDate();
      this.valueri.push(yesterdayYear + '-' + yesterdayMonth + '-' +yesterdayDay+' '+'00'+':'+'00'+':'+'00')
      this.valueri.push(year+'-'+month+'-'+day+' '+'00'+':'+'00'+':'+'00')
    },
    // 多选
    handleCheckAllChange(val) {
      const arr=this.leilist.map(ele=>ele.value)
        this.checkedCities = val ? arr : [];
      this.isIndeterminate = false;
    },
      // 单选
      handleCheckedCitiesChange(value) {
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.leilist.length;
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.leilist.length;
      }
  },
  watch: {
    filterText (newValue) {
      this.filterText = newValue.replace(/^\[(.*?)\]/, '').replace(/\((.*?)\)$/, '')
    },
  }
};
</script>

<style lang="scss" scoped>
.bigbox{
  padding: 10px;
  height: 100%;
  display: flex;
  .leftbox{
    width: 300px;
    height: 100%;
    background-color: #fff;
    padding: 20px;
    .treebox{
      height: 95%;
      overflow: hidden;
      overflow-y: auto;
    }
  }
  .bodybox{
    width: calc(100% - 310px);
    margin-left: 10px;
    .sousuo{
      height: 80px;
      margin-bottom: 10px;
      background-color: #fff;
      padding:20px;
    }
    .xunhuan{
      height: 120px;
      padding: 20px;
      background-color: #fff;
      margin-bottom: 10px;
    }
    .zhuti{
      height: calc(100% - 220px);
      background-color: #fff;
      padding: 20px;
      .toptitle{
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;
      }
      .table{
        height: 93%;
      }
    }
  }
}
::v-deep .el-checkbox-group{
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
::v-deep .el-checkbox{
 width: 12%;
 margin-bottom: 10px;
}
::v-deep .el-tree-node.is-current > .el-tree-node__content {
  background-color: #bae7ff !important;
}
::v-deep .el-tree-node__content{
  &:hover{
    background-color: #f0f7ff;
  }
}
::v-deep .el-tree-node__content {
  font-size: 14px; /* 修改为你想要的字体大小 */
}
</style>